package main

import (
	"fyne.io/fyne/v2"
	"image"
	"image/jpeg"
	"image/png"
	"os"

	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
)

func main() {
	myApp := app.New()
	myWindow := myApp.NewWindow("Replace Image Example")

	// 加载第一张图像
	img1Path := "gui/WidgetTemplet/Error.png"
	canvasImage := loadImage(img1Path)

	// 创建按钮来替换图像
	replaceButton := widget.NewButton("Replace Image", func() {
		img2Path := "gui/WidgetTemplet/Button_Close.png" // 替换为第二张图像的路径
		img2 := loadImage2(img2Path)
		canvasImage.Image = *img2 // 替换图像
		//canvasImage.SetMinSize(canvasImage.Image.Bounds().Size()) // 更新最小尺寸
		canvasImage.Refresh() // 刷新显示
	})

	// 将图像和按钮添加到容器中
	content := container.NewVBox(replaceButton, canvasImage)
	myWindow.SetContent(content)
	myWindow.Resize(fyne.NewSize(400, 400))
	myWindow.ShowAndRun()
}

// 加载图像的函数
func loadImage(imgPath string) *canvas.Image {
	imgFile, err := os.Open(imgPath)
	if err != nil {
		panic(err)
	}
	defer imgFile.Close()

	var img image.Image
	if ext := getFileExtension(imgPath); ext == ".png" {
		img, err = png.Decode(imgFile)
	} else if ext == ".jpg" || ext == ".jpeg" {
		img, err = jpeg.Decode(imgFile)
	} else {
		panic("unsupported image format")
	}

	if err != nil {
		panic(err)
	}
	canvasImage := canvas.NewImageFromImage(img)
	_min := img.Bounds().Min
	_max := img.Bounds().Max
	var _size = fyne.NewSize(float32(_max.X-_min.X), float32(_max.Y-_min.Y))
	canvasImage.Resize(_size)
	canvasImage.SetMinSize(_size)
	return canvasImage
	//return img
}

// 加载图像的函数
func loadImage2(imgPath string) *image.Image {
	imgFile, err := os.Open(imgPath)
	if err != nil {
		panic(err)
	}
	defer imgFile.Close()

	var img image.Image
	if ext := getFileExtension(imgPath); ext == ".png" {
		img, err = png.Decode(imgFile)
	} else if ext == ".jpg" || ext == ".jpeg" {
		img, err = jpeg.Decode(imgFile)
	} else {
		panic("unsupported image format")
	}

	if err != nil {
		panic(err)
	}
	return &img
}

// 获取文件扩展名
func getFileExtension(filename string) string {
	if len(filename) < 4 {
		return ""
	}
	return filename[len(filename)-4:]
}
